import React, { useState, useRef, useEffect } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { PowerDevice } from '../../../types';

interface PowerDeviceProps {
  device: PowerDevice;
  isSelected?: boolean;
  onClick?: () => void;
}

const PowerDeviceComponent: React.FC<PowerDeviceProps> = ({
  device,
  isSelected = false,
  onClick
}) => {
  const groupRef = useRef<THREE.Group>(null);
  const [isHovered, setIsHovered] = useState(false);
  const [rotationSpeed, setRotationSpeed] = useState(0);

  // 根据设备类型获取颜色
  const getDeviceColor = (): string => {
    switch (device.type) {
      case 'PDU':
        return '#3F51B5'; // 深蓝色
      case 'UPS':
        return '#009688'; // 青绿色
      case 'Transformer':
        return '#FF9800'; // 橙色
      case 'Generator':
        return '#795548'; // 棕色
      default:
        return '#607D8B'; // 蓝灰色
    }
  };

  // 根据设备状态获取颜色
  const getStatusColor = (): string => {
    switch (device.status) {
      case 'online':
        return '#4CAF50';
      case 'offline':
        return '#9E9E9E';
      case 'warning':
        return '#FFC107';
      case 'error':
        return '#F44336';
      default:
        return '#2196F3';
    }
  };



  // 处理点击事件
  const handleClick = (event: React.MouseEvent) => {
    event.stopPropagation();
    if (onClick) {
      onClick();
    }
  };

  // 处理鼠标悬停事件
  const handleMouseEnter = () => {
    setIsHovered(true);
  };

  const handleMouseLeave = () => {
    setIsHovered(false);
  };

  // 根据设备类型设置旋转速度（模拟运行状态）
  useEffect(() => {
    if (device.status === 'online') {
      switch (device.type) {
        case 'Generator':
          setRotationSpeed(0.05);
          break;
        case 'Transformer':
          setRotationSpeed(0.03);
          break;
        default:
          setRotationSpeed(0);
      }
    } else {
      setRotationSpeed(0);
    }
  }, [device.status, device.type]);

  // 旋转动画效果
  useFrame(() => {
    if (groupRef.current && rotationSpeed > 0) {
      // 可以在这里添加旋转动画逻辑
      // 例如：groupRef.current.rotation.y += rotationSpeed;
    }
  });

  // 根据设备类型创建不同的模型
  const renderDeviceModel = () => {
    const color = getDeviceColor();
    const hasRotatingPart = device.type === 'Generator' || device.type === 'Transformer';
    
    switch (device.type) {
      case 'PDU':
        // PDU模型 - 矩形盒体
        return (
          <group>
            <mesh position={[0, 0.2, 0]}>
              <boxGeometry args={[0.6, 0.3, 0.2]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.4} />
            </mesh>
            
            {/* PDU插座 */}
            <group position={[0, 0.1, -0.1]}>
              {Array.from({ length: 6 }).map((_, index) => (
                <mesh
                  key={`socket-${index}`}
                  position={[-0.25 + (index % 3) * 0.25, 0.15 - Math.floor(index / 3) * 0.15, 0]}
                >
                  <boxGeometry args={[0.08, 0.08, 0.02]} />
                  <meshStandardMaterial color="#424242" roughness={0.8} metalness={0.2} />
                </mesh>
              ))}
            </group>
          </group>
        );
        
      case 'UPS':
        // UPS模型 - 长方体带散热孔
        return (
          <group>
            <mesh position={[0, 0.3, 0]}>
              <boxGeometry args={[0.8, 0.5, 0.4]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.4} />
            </mesh>
            
            {/* 散热孔 */}
            <group position={[0, 0.3, 0.21]}>
              {Array.from({ length: 8 }).map((_, index) => (
                <mesh
                  key={`vent-${index}`}
                  position={[-0.3 + (index % 4) * 0.2, 0.3 - Math.floor(index / 4) * 0.2, 0]}
                >
                  <boxGeometry args={[0.15, 0.1, 0.01]} />
                  <meshStandardMaterial color="#212121" roughness={0.8} metalness={0.3} />
                </mesh>
              ))}
            </group>
          </group>
        );
        
      case 'Transformer':
        // 变压器模型 - 立方体带线圈
        return (
          <group>
            <mesh position={[0, 0.25, 0]}>
              <boxGeometry args={[0.5, 0.5, 0.3]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.4} />
            </mesh>
            
            {/* 线圈 */}
            {hasRotatingPart && (
              <mesh position={[0, 0.25, 0]} rotation={[0, Math.PI * 0.25, 0]}>
                <torusGeometry args={[0.3, 0.05, 10, 30]} />
                <meshStandardMaterial color="#FFD740" roughness={0.4} metalness={0.6} />
              </mesh>
            )}
          </group>
        );
        
      case 'Generator':
        // 发电机模型 - 圆柱体带风扇
        return (
          <group>
            <mesh position={[0, 0.3, 0]}>
              <cylinderGeometry args={[0.4, 0.4, 0.6, 12]} />
              <meshStandardMaterial color={color} roughness={0.7} metalness={0.5} />
            </mesh>
            
            {/* 风扇 */}
            {hasRotatingPart && (
              <mesh position={[0, 0.3, -0.31]}>
                <circleGeometry args={[0.3, 8]} />
                <meshStandardMaterial color="#F5F5F5" roughness={0.5} metalness={0.3} />
              </mesh>
            )}
          </group>
        );
        
      default:
        // 默认模型
        return (
          <mesh position={[0, 0.3, 0]}>
            <boxGeometry args={[0.6, 0.5, 0.4]} />
            <meshStandardMaterial color={color} roughness={0.6} metalness={0.4} />
          </mesh>
        );
    }
  };

  return (
    <group
      ref={groupRef}
      position={[device.position.x, device.position.y, device.position.z]}
      onClick={handleClick}
      onPointerEnter={handleMouseEnter}
      onPointerLeave={handleMouseLeave}
    >
      {/* 设备底座 */}
      <mesh position={[0, 0, 0]}>
        <boxGeometry args={[1, 0.1, 0.8]} />
        <meshStandardMaterial color="#424242" roughness={0.8} metalness={0.3} />
      </mesh>
      
      {/* 设备主体 */}
      {renderDeviceModel()}
      
      {/* 状态指示器 */}
      <mesh
        position={[0, 0.6, 0]}
      >
        <sphereGeometry args={[0.08]} />
        <meshStandardMaterial
          color={getStatusColor()}
          emissive={getStatusColor()}
          emissiveIntensity={0.6}
          roughness={0.2}
          metalness={0.3}
        />
      </mesh>
      
      {/* 选中边框 */}
      {isSelected && (
        <lineSegments>
          <edgesGeometry
            args={[
              new THREE.BoxGeometry(1.2, 1.2, 1)
            ]}
          />
          <lineBasicMaterial
            color="#2196F3"
            linewidth={3}
          />
        </lineSegments>
      )}
      
      {/* 悬停效果 */}
      {isHovered && (
        <lineSegments>
          <edgesGeometry
            args={[
              new THREE.BoxGeometry(1.1, 1.1, 0.9)
            ]}
          />
          <lineBasicMaterial
            color="#64B5F6"
            linewidth={2}
          />
        </lineSegments>
      )}
      
      {/* 如果有UPS电池信息，显示电池电量 */}
      {device.type === 'UPS' && device.batteryLevel !== undefined && (
        <mesh position={[0, 0.7, 0]} rotation={[-Math.PI / 2, 0, 0]}>
          <planeGeometry args={[0.3, 0.15]} />
          <meshStandardMaterial color="#FFFFFF" roughness={0.5} metalness={0.1} />
          {/* 这里可以添加电池电量的文本显示 */}
        </mesh>
      )}
    </group>
  );
};

export default React.memo(PowerDeviceComponent);